package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/locales/en"
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	en_translations "github.com/go-playground/validator/v10/translations/en"
	zh_translations "github.com/go-playground/validator/v10/translations/zh"
	"net/http"
	"reflect"
	"strings"
)

type SignUpForm struct {
	Age        uint8  `json:"age" binding:"gte=1,lte=130"`
	Name       string `json:"name" binding:"required,min=3"`
	Email      string `json:"email" binding:"required,email"`
	Password   string `json:"password" binding:"required"`
	RePassword string `json:"re_password" binding:"required,eqfield=Password"`
}

var trans ut.Translator

func removeTopStruct(fileds map[string]string) map[string]string {
	rsp := map[string]string{}
	for field, err := range fileds {
		rsp[field[strings.Index(field,".")+1:]] = err
	}
	return rsp
}

func InitTrans(locale string) (err error) {
	// 修改gin框架中的validator 引擎属性，实现定制；将gin中的validator转为 go-playground/validator 中的validator
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		// 将字段改成json对应里的字段
		v.RegisterTagNameFunc(func(fld reflect.StructField)string{
			name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
			if name == "-"{
				return ""
			}
			return name
		})


		zhT := zh.New() // 中文翻译器
		enT := en.New() // 英文翻译器s
		// 第一个参数是备用语言环境，后面参数是应该支持的余元环境
		uni := ut.New(enT, zhT, enT)
		trans, ok = uni.GetTranslator(locale)
		if  !ok {
			fmt.Errorf("uni.GetTranslator（%s）", err.Error())
		}
		switch locale{
		case "en":
			en_translations.RegisterDefaultTranslations(v, trans)
		case "zh":
			zh_translations.RegisterDefaultTranslations(v, trans)
		default:
			en_translations.RegisterDefaultTranslations(v, trans)
		}
		return
	}
	return
}

func main() {
	if err := InitTrans("zh"); err != nil {
		fmt.Println("获取翻译器错误")
		return
	}

	router := gin.Default()

	router.POST("/sign", login)

	router.Run(":8686")
}

func login(c *gin.Context) {
	var loginInfo SignUpForm
	if err := c.ShouldBind(&loginInfo); err != nil {
		errs, ok := err.(validator.ValidationErrors)
		if !ok {
			c.JSON(http.StatusBadRequest,gin.H{
				"msg": err.Error(),
			})
		}
		c.JSON(http.StatusBadRequest, gin.H{
			"err": removeTopStruct(errs.Translate(trans)),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"message": "注册成功！",
	})
}
